<template>
  <Modal :mask-closable="false"
          v-model="visible"
          width="1000"
          class="addModal"
          :title="!id ? '新增精度检测项目' : '编辑精度检测项目'"
  >
    <div class="addProject">
      <div class="titleItem">
        <span>检测对象</span>
        <div class="checkObject">
          <div class="checkObjectItem">
            <div class="checkObjectName" :class="{ required: true }" >{{$t('maintenance.EquipmentType')}}</div>
            <div class="checkObjectValue">
              <Select
                      v-model="formInline.categoryId"
                      filterable
                      clearable
                      :placeholder="`${$t('common.selectInfo')}`"
                      class="select"
              >
                <Option v-for="v in deviceList" :value="v.value" :key="v.value">{{
                  v.label
                  }}</Option>
              </Select>
            </div>
          </div>
          <div class="checkObjectItem">
            <div class="checkObjectName" :class="{ required: true }">检测位置</div>
            <div class="checkObjectValue">
              <Select
                      v-model="formInline.positionId"
                      filterable
                      clearable
                      :placeholder="`${$t('common.selectInfo')}`"
                      class="select"
              >
                <Option v-for="v in positionList" :value="v.value" :key="v.value">{{
                  v.label
                  }}</Option>
              </Select>
            </div>
          </div>
          <div class="checkObjectItem">
            <div class="checkObjectName" :class="{ required: true }">检测分类</div>
            <div class="checkObjectValue">
              <Select
                      v-model="formInline.classifyId"
                      filterable
                      clearable
                      :placeholder="`${$t('common.selectInfo')}`"
                      class="select"
              >
                <Option v-for="v in classifyList" :value="v.value" :key="v.value">{{
                  v.label
                  }}</Option>
              </Select>
            </div>
          </div>
        </div>
      </div>
      <div class="titleItem">
        <span>检测时间</span>
        <div class="checkObject">
          <div class="checkObjectItem" style="flex: 1">
            <div class="checkObjectName" :class="{ required: true }" style="width: 15%;">检测周期</div>
            <div class="checkObjectValue" style="width: 85%;">
              <CheckboxGroup v-model="formInline.triggerCycle">
                <Checkbox v-for="(m, n) in weeks" :key="n" :label="m.label">{{ m.name }}</Checkbox>
              </CheckboxGroup>
            </div>
          </div>
        </div>
      </div>
      <div class="titleItem">
        <span>检测内容</span>
        <div class="checkObject" style="padding: 0 0">
          <div class="checkObjectItem" style="flex: 1;">
            <div class="checkObjectName" style="width: 15%;" :class="{ required: true }">检测项目</div>
            <div class="checkObjectValue" style="width: 85%;">
              <Input :maxlength="100" class="inputWrapper" v-model="formInline.itemProject" clearable/>
            </div>
          </div>
        </div>
        <div class="checkObject" style="padding: 0 0">
          <div class="checkObjectItem" style="flex: 1;">
            <div class="checkObjectName" style="width: 15%;" :class="{ required: true }">检测方法</div>
            <div class="checkObjectValue" style="width: 85%;">
              <Input :maxlength="250" class="inputWrapper" v-model="formInline.itemMethod" clearable/>
            </div>
          </div>
        </div>
      </div>
      <div class="titleItem">
        <span>检测标准</span>
        <div class="checkObject">
          <div class="checkObjectItem">
            <div class="checkObjectName">{{$t('maintenance.LowerLimit')}}</div>
            <div class="checkObjectValue">
              <InputNumber :max="9999999999999999999" class="inputNumberWrapper" v-model="formInline.minValue" clearable/>
            </div>
          </div>
          <div class="checkObjectItem">
            <div class="checkObjectName" >{{$t('maintenance.UpperLimit')}}</div>
            <div class="checkObjectValue">
              <InputNumber :max="9999999999999999999" class="inputNumberWrapper" v-model="formInline.maxValue" clearable/>
            </div>
          </div>
          <div class="checkObjectItem">
            <div class="checkObjectName">{{$t('maintenance.Unit')}}</div>
            <div class="checkObjectValue">
              <Input :maxlength="19" class="inputWrapper" v-model="formInline.unitName" clearable/>
            </div>
          </div>
          <div class="checkObjectItem">
            <div class="checkObjectName" :class="{ required: true }">{{$t('maintenance.workinghours')}}</div>
            <div class="checkObjectValue">
              <InputNumber class="inputNumberWrapper" :min="1" :max="9999999999999999999" v-model="formInline.itemHours" clearable/>
            </div>
          </div>
        </div>
      </div>
      <div class="titleItem tab">
        <span>检测使用工具</span>
        <div class="icon" @click="handleUseTools"><Icon type="md-add" color="#187BDB" />添加工具</div>
      </div>
      <div class="tableContent">
        <Table ellipsis ref="selection" :columns="columns" :data="toolsData">
          <template slot-scope="{row, index}" slot="toolNum">
            <div v-if="!row.isEdit">
              <Row>
                <Col :span="20">
                  <span>{{row.toolNum}}</span>
                </Col>
                <Col :span="4">
                  <Icon type="ios-brush-outline" size="18" color="#180fff" @click="handleToolsEdit(row,index)"></Icon>
                </Col>
              </Row>
            </div>
            <div v-else>
              <Row>
                <Col :span="20">
                  <Input clearable :value="row.toolNum" @on-change="handleToolsChange($event,index)"></Input>
                </Col>
                <Col :span="4">
                  <Icon type="ios-checkmark" size="35" color="#180fff" @click="handleUnToolsEdit(row,index)" style="display: inline-block"></Icon>
                </Col>
              </Row>
            </div>
          </template>
          <template slot-scope="{row}" slot="action">
<!--            <span class="operationBtn" @click="handleToolsEdit(row,index)">{{$t('common.Edit')}}</span>-->
            <span class="operationBtn" @click="handleToolsDelete(row)">{{$t('common.Delete')}}</span>
          </template>
        </Table>
      </div>
      <div class="titleItem tab">
        <span>检测使用物料</span>
        <div class="icon" @click="handleUseGoods"><Icon type="md-add" color="#187BDB" />添加物料</div>
      </div>
      <div class="tableContent">
        <Table ellipsis ref="selection" :columns="wlColumns" :data="wlData">
          <template slot-scope="{row, index}" slot="num">
            <div v-if="!row.isEdit">
              <Row>
                <Col :span="20" >
                  <span>{{row.num}}</span>
                </Col>
                <Col :span="4">
                  <Icon type="ios-brush-outline" size="18" color="#180fff" @click="handleGoodsEdit(row,index)"></Icon>
                </Col>
              </Row>
            </div>
            <div v-else>
              <Row>
                <Col :span="20">
                  <Input clearable :value="row.toolNum"
                         @on-keyup="levelCheck"
                         @on-change="handleGoodsChange($event,index,row)"></Input>
                </Col>
                <Col :span="4">
                  <Icon type="ios-checkmark" size="35" color="#180fff" @click="handleUnGoodsEdit(row,index)" style="display: inline-block"></Icon>
                </Col>
              </Row>
            </div>
          </template>
          <template slot-scope="{row}" slot="action">
            <!--            <span class="operationBtn" @click="handleToolsEdit(row,index)">{{$t('common.Edit')}}</span>-->
            <span class="operationBtn" @click="handleGoodsDelete(row)">{{$t('common.Delete')}}</span>
          </template>
        </Table>
      </div>
      <use-tools-modal ref="userToolsModal" @handleSelectUseTools="handleSelectUseTools"/>
      <use-goods-modal ref="userGoodsModal" @handleUseGoodsOk="handleUseGoodsOk"/>
    </div>

    <div slot="footer">
      <Button type="default" @click="visible = false">{{$t('common.Cancle')}}</Button>
      <Button type="primary" :loading="loadingVisible" @click="handleOk">{{$t('maintenance.Confirmed')}}</Button>
    </div>
  </Modal>
</template>

<script>
import UseToolsModal from "./useToolsModal";
import UseGoodsModal from "./useGoodsModal";
export default {
  name: "addModal",
  components: {UseGoodsModal, UseToolsModal},
  props: [],
  data() {
    return {
      id: '',
      formInline: {
        triggerCycle: [],
        maxValue: null,
        minValue: null,
        itemHours: null
      },
      visible: false,
      loadingVisible: false,
      deviceList: [],
      positionList: [],
      classifyList: [],
      weeks: [
        { name: "日", label: "1" },
        { name: "周", label: "2" },
        { name: "月", label: "3" },
        { name: "季度", label: "4" },
        { name: "半年", label: "5" },
        { name: "年度", label: "6" },
        // { name: "计数", label: "7" },
        // { name: "计时", label: "8" },
      ],
      columns: [
        {
          title: '物料代码',
          key: 'toolCode'
        },
        {
          title: '使用工具',
          key: 'toolName'
        },
        {
          title: `${ this.$t('equipCheck.Model') }`,
          key: 'toolModel'
        },
        {
          title: '品牌',
          key: 'toolBrand'
        },
        // {
        //   title: `${this.$t('spareParts.quantity')}`,
        //   key: 'toolNum',
        //   slot: 'toolNum'
        // },
        {
           title: `${ this.$t('maintenance.safekeeping') }`,
          key: 'keepType'
        },
        {
          title: `${ this.$t('common.operation') }`,
          key: 'action',
          slot: 'action'
        }
      ],
      wlColumns: [
        { title: `${ this.$t('maintenance.materialcode') }`, key: "maCode" },
        { title: `${ this.$t('maintenance.materialname') }`, key: "maName" },
        { title: `${ this.$t('spareParts.quantity') }`, key: "num", slot: 'num' },
        { title: `${ this.$t('maintenance.Unitprice') }`, key: "maPrice" },
        { title: `${ this.$t('maintenance.totalprice') }`, key: "totalPrice" },
        { title: `${ this.$t('common.operation') }`, key: 'action', slot: 'action'}
      ],
      toolsData: [],
      wlData: [],
    };
  },
  created() {
    this.getDeviceList()
    this.getPositionList()
    this.getClassifyList()
  },
  methods: {
    /**************基础数据**********************/
    getDeviceList() {
      this.axios({
        method: 'get',
        url: '/dms/dmsCategory/getSelectList',
        params: {}
      }).then(res => {
        if(res.code === 200){
          this.deviceList = res.data
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    getPositionList() {
      this.axios({
        method: 'get',
        url: '/dms/dcmAcctestPosition/getSelectList',
        params: {}
      }).then(res => {
        if(res.code === 200){
          this.positionList = res.data
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    getClassifyList() {
      this.axios({
        method: 'get',
        url: '/dms/dcmAcctestClassify/getSelectList',
        params: {}
      }).then(res => {
        if(res.code === 200){
          this.classifyList = res.data
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    show(row) {
      this.id = row.id
      if (!this.id) {
        this.formInline = {
          maxValue: null,
          minValue: null,
          itemHours: null
        }
        this.toolsData = []
        this.wlData = []
        this.visible = true
      }else {
        this.visible = true
        this.getDetail(this.id)
      }


    },
    getDetail(id) {
      this.axios({
        method: 'get',
        url: '/dms/dcmAcctestItem/queryById',
        params: {
          id
        }
      }).then(res => {
        if (res.code === 200) {
          this.$nextTick(() => {
            this.formInline = {
              ...res.data,
              triggerCycle: res.data.triggerCycle ? res.data.triggerCycle.split(','): [],
              minValue: Number(res.data.min_value),
              maxValue: Number(res.data.max_value)
            }
            this.wlData = res.data.dcmAcctestMaterialList.map(item => {
              return {
                ...item,
                maCode: item.materialCode,
                maName: item.materialName,
                maPrice: item.unitPrice,
                isEdit: false,
              }
            })
            this.toolsData = res.data.dcmAcctestToolList.map(item => {
              return {
                ...item,
                isEdit: false,
              }
            })
          })
        }else {
          this.$Message.warning(({content:res.msg,duration:6,closable:true}))
        }
      })
    },
    handleToolsChange(event, index) {
      this.toolsData[index].toolNum = event.target.value
    },
    handleToolsEdit(row,index) {
      this.toolsData[index].isEdit = true
    },
    levelCheck(e){
      e.target.value = e.target.value.replace(/(^\s*)|(\s*$)/g, "");
      const reg = /[^\d.]/g;
      e.target.value = e.target.value.replace(reg, "");
      e.target.value = e.target.value.replace(/^\./g, "");
      e.target.value = e.target.value
              .replace(".", "$#$")
              .replace(/\./g, "")
              .replace("$#$", ".");
      e.target.value = e.target.value.replace(
              /^(\-)*(\d+)\.(\d\d).*$/,
              "$1$2.$3"
      )
    },
    handleUnToolsEdit(row,index) {
      this.toolsData[index].isEdit = false
    },
    handleGoodsChange(event, index, row) {
      this.wlData[index].num = event.target.value
      this.wlData[index].totalPrice = parseFloat(Number(row.maPrice) * Number(event.target.value)).toFixed(2)
    },
    handleGoodsEdit(row,index) {

      this.wlData[index].isEdit = true
    },
    handleUnGoodsEdit(row,index) {
        this.wlData[index].isEdit = false
    },
    handleGoodsDelete(row) {
      this.wlData = this.wlData.filter(item => item.id != row.id)
    },
    handleToolsDelete(row) {
      this.toolsData = this.toolsData.filter(item => item.id != row.id)
    },
    handleUseTools() {
      this.$refs.userToolsModal.show()
    },
    handleSelectUseTools(data) {
      this.toolsData = [...this.toolsData, ...data]
      // if (this.toolsData.length) {
      //   let arr = this.toolsData.filter(item => data.some(x => x.id == item.id))
      //   console.log(arr)
      //   if (arr.length) {
      //     this.$Message.warning(({content: '有重复数据，请重新选择！', duration: 6, closable: true}));
      //     return false
      //   }
      //   this.toolsData = [...this.toolsData, ...data]
      // }else {
      //   this.toolsData = [...this.toolsData, ...data]
      // }
    },
    handleUseGoods() {
      this.$refs.userGoodsModal.show()
    },
    handleUseGoodsOk(data) {
      // this.wlData.push(data)
      this.wlData = [...this.wlData, ...data]
    },
    handleOk() {
      let triggerCycle = this.formInline.triggerCycle ? this.formInline.triggerCycle.toString() : ''
      if (!this.formInline.categoryId || !this.formInline.positionId || !this.formInline.classifyId || !triggerCycle || !this.formInline.itemProject || !this.formInline.itemMethod || !this.formInline.itemHours) {
        this.$Message.warning(({content:'请将信息填写完整！',duration:6,closable:true}))
        return false
      }
      if (this.formInline.minValue > this.formInline.maxValue) {
        this.$Message.warning(({content:'下限不能大于上限！',duration:6,closable:true}))
        return false
      }
      let dcmAcctestMaterialList = []
      let dcmAcctestToolList = []
      dcmAcctestMaterialList = this.wlData.map(item => {
        return {
          materialCode: item.maCode,
          materialName: item.maName,
          num: item.num,
          totalPrice: item.totalPrice,
          unitPrice: item.maPrice
        }
      })
      dcmAcctestToolList = this.toolsData.map(item => {
        return {
          toolId: item.toolId ? item.toolId : item.id ,
          toolNum: item.toolNum
        }
      })
      let data = {
        ...this.formInline,
        triggerCycle,
        dcmAcctestMaterialList,
        dcmAcctestToolList
      }
      if (!this.id) {
        this.axios({
          method: 'get',
          url: '/dms/dcmAcctestItem/validItemProject',
          params: {
            itemProject: this.formInline.itemProject
          }
        }).then(res => {
          if (res.code == 200) {
            this.loadingVisible = true
            this.axios({
              method: 'post',
              url: '/dms/dcmAcctestItem/add',
              data
            }).then(res => {
              if (res.code === 200) {
                this.visible = false
                this.$emit('handleSearch')
                this.$Message.success(({content:'新增成功！',duration:2,closable:true}))
              }else {
                this.$Message.warning(({content:res.msg,duration:6,closable:true}))
              }
            }).finally(() => {
              this.loadingVisible = false
            })
          }else {
            this.$Message.warning(({content:res.msg,duration:6,closable:true}))
          }
        })

      }else {
        this.axios({
          method: 'get',
          url: '/dms/dcmAcctestItem/validItemProject',
          params: {
            id: this.id,
            itemProject: this.formInline.itemProject
          }
        }).then(res => {
          if (res.code == 200) {
            this.loadingVisible = true
            this.axios({
              method: 'put',
              url: '/dms/dcmAcctestItem/edit',
              data
            }).then(res => {
              if (res.code === 200) {
                this.visible = false
                this.$emit('handleSearch')
                this.$Message.success(({content:'编辑成功！',duration:2,closable:true}))
              }else {
                this.$Message.warning(({content:res.msg,duration:6,closable:true}))
              }
            }).finally(() => {
              this.loadingVisible = false
            })
          }else {
            this.$Message.warning(({content:res.msg,duration:6,closable:true}))
          }
        })
      }

    }
  },
};
</script>

<style lang="scss">
.addProject {
  .titleItem {
    position: relative;
    font-size: 18px;
    font-weight: bold;
    padding: 10px;
    .checkObject {
      display: flex;
      flex-wrap: wrap;
      padding: 20px 0;
      font-family: 'Arial Normal', 'Arial', sans-serif;
      font-weight: 400;
      font-style: normal;
      letter-spacing: normal;
      .checkObjectItem {
        display: flex;
        flex: 0 50%;
        .checkObjectName {
          height: 40px;
          line-height: 40px;
          width: 30%;
          font-size: 13px;
          border: 1px solid #eeeeee;
          background: #f5f6f7;
          text-align: right;
          padding-right: 10px;
          color: #666666;
        }
        .required::before {
          content: "*";
          color: red;
        }
        .checkObjectValue {
          height: 40px;
          line-height: 40px;
          width: 70%;
          font-size: 13px;
          border: 1px solid #eeeeee;
          padding-left: 10px;
          color: #333;
          .select {
            .ivu-select-selection {
              border: none;
              box-shadow: none;
              font-size: 13px;
            }
          }
          .inputWrapper {
            .ivu-input {
              border: none;
              box-shadow: none;
            }
          }
        }
      }
    }
    .searchBox {
      .label {
        display: flex;
      }
    }
    .contentTable {
      padding: 20px;
    }
  }
  .titleItem::before {
    content: "";
    position: absolute;
    width: 3px;
    height: 20px;
    top: 13px;
    left: 0px;
    background: #187bdb;
  }
  .tab {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    .icon {
      border: 1px solid #187bdb;
      border-radius: 30px;
      padding: 5px 20px 5px 20px;
      display: flex;
      align-items: center;
      margin-left: 20px;
      color: #187bdb;
      i {
        font-size: 20px;
        font-weight: bold;
      }
    }
  }
}
</style>
